package wf3.servlet;

import acceso.util.Escritor;
import acceso.util.UserSesion;
import acceso.util.WorkflowUtil;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import wf.dto.login.pppermis;
import wf.dto.login.ppregsesiniDto;
import wf3.core.dao.LoginDAO;
import wf3.core.manager.DAOFactory;
import wf3.kernel.WorkflowFactory;

/**
 *
 * @author Rómulo Galindo Tanta
 */
public class WorkflowLoginServlet extends HttpServlet {

    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=ISO-8859-1");
        PrintWriter out = response.getWriter();

        //variables de uso global
        HttpSession session = request.getSession();

        //------------------------------------------
        int p_modowf;
        /**
         * xact (1) Logearse xact (2) Deslogearse
         */
        String xact = request.getParameter("xact");
        System.out.println("[Login]Ejecutandose el xact: " + xact);
        try {
            if (xact != null) {
                switch (xact) {
                    case "2": {//DESLOGEARSE
                        session.invalidate();
                        Cookie[] cookies = request.getCookies();
                        Cookie cookie = new Cookie(WorkflowFactory.getConfiguration().getCookie_name(), "");
                        for (int i = 0; i < cookies.length; i++) {
                            System.out.println("0");
                            if (cookies[i].getName().contentEquals(WorkflowFactory.getConfiguration().getCookie_name())) {
                                cookie.setComment(cookies[i].getComment());
                                cookie.setDomain(WorkflowFactory.getConfiguration().getCookie_domain());
                                cookie.setPath("/");
                                cookie.setSecure(cookies[i].getSecure());
                                cookie.setVersion(cookies[i].getVersion());
                                cookie.setMaxAge(0);
                                System.out.println("[Login]cookie modificado: " + cookie.getMaxAge());
                                response.addCookie(cookie);
                            }
                        }
                        response.sendRedirect(request.getContextPath());
                        break;
                    }
                    case "3": {
                        String id_sesion = request.getParameter("id_sesion");
                        if (id_sesion != null & !id_sesion.isEmpty()) {
                            LoginDAO loginDao = new LoginDAO();
                            ppregsesiniDto ppresses = loginDao.SESION(Long.parseLong(id_sesion));
                            loginDao.CLOSE_SESSION();
                            out.print(new Gson().toJson(ppresses));
                        } else {
                            out.print("null");
                        }
                        break;
                    }
                    case "4": {
                        p_modowf = WorkflowUtil.convertir_entero(request.getParameter("p_modowf"), -1);
                        String p_sesion = request.getParameter("p_sesion");
                        String p_co_sistem = request.getParameter("p_co_sistem");

                        if (p_modowf > -1 && (p_sesion != null & !p_sesion.isEmpty()) && (p_co_sistem != null & !p_co_sistem.isEmpty())) {
                            LoginDAO loginDao = new LoginDAO();
                            pppermis permis = loginDao.PERMIS(Integer.parseInt(p_sesion), Short.parseShort(p_co_sistem));
                            out.print(new Gson().toJson(permis));
                        } else {
                            out.print("null");
                        }
                        break;
                    }
                    default: {
                        response.sendRedirect("/");
                        break;
                    }
                }
            } else {
                RequestDispatcher dispatcher = request.getRequestDispatcher("login/login.jsp");
                dispatcher.forward(request, response);
            }

        } catch (Exception e) {
            Escritor.escribe_errors("Error: " + e.getMessage() + "," + e.getClass() + "," + e.getCause());
            response.sendRedirect("");
            out.print(e);
        } finally {
            out.close();
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        processRequest(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        PrintWriter out = response.getWriter();
        Escritor.escribe_debug("logeanose en metodo post");

        //variables de uso global
        HttpSession session = request.getSession();
        LoginDAO DAO;
        UserSesion US;

        String p_usuari;
        String p_passwo;
        String p_ipaddr;
        String p_navega;
        String p_dirurl;
        String p_usuage;
        boolean p_mobile;
        int p_cosyst;

        String xact = request.getParameter("xact");
        try {
            switch (xact) {
                case "1": {//LOGEARSE
                    p_usuari = request.getParameter("p_usuari");//usuario del sistema
                    p_passwo = request.getParameter("p_passwo");//password del sistema
                    p_navega = request.getParameter("p_navega");//password del sistema
                    p_dirurl = request.getParameter("p_dirurl");//password del sistema
                    p_usuage = request.getHeader("user-agent");
                    p_mobile = WorkflowUtil.convertir_boolean(request.getParameter("p_mobile"), false);//password del sistema
                    p_ipaddr = request.getRemoteAddr();//password del sistema
                    p_cosyst = WorkflowUtil.convertir_entero(session.getServletContext().getInitParameter("co_system"), 1);//codigo del sistema
                    DAO = (LoginDAO) DAOFactory.get_logindao();
                    try {
                        ppregsesiniDto ppregses = DAO.SESION(p_usuari, p_passwo, 0, p_usuage, p_ipaddr, p_cosyst);
                        pppermis permisos = DAO.PERMIS(ppregses.getId_sesion(), (short) p_cosyst);
                        DAO.CLOSE_SESSION();

                        US = new UserSesion(ppregses, permisos, p_navega, p_mobile);
                        US.setIs_mac(WorkflowUtil.isMac(p_usuage));
                        session.setAttribute("US", US);

                        Cookie cookie = new Cookie(WorkflowFactory.getConfiguration().getCookie_name(), "" + US.getId_sesion());
                        cookie.setDomain(WorkflowFactory.getConfiguration().getCookie_domain());
                        cookie.setPath("/");
                        cookie.setHttpOnly(true);

                        response.addCookie(cookie);
                        response.addHeader("Refresh", "0; URL=" + (p_dirurl == null ? US.getNo_modini() : p_dirurl));
                        out.print("Cargando...");
                    } catch (Exception ep) {
                        DAO.CLOSE_SESSION();
                        request.setAttribute("p_error", WorkflowUtil.getMSGError(ep));

                        Escritor.escribe_errors("[LoginServlet]error:" + ep.getMessage());

                        RequestDispatcher dispatcher = request.getRequestDispatcher("/login/login.jsp");
                        dispatcher.forward(request, response);
                    }
                    break;
                }
            }

        } catch (ServletException | IOException ep) {
            Escritor.escribe_errors("[LoginServlet]error general:" + ep.getMessage());
            ep.printStackTrace();
        } finally {
            out.close();
        }
    }

    @Override
    public String getServletInfo() {
        return "Servlet Workflow Login";
    }
}
